<template>
  <el-dialog v-if="load" :close-on-click-modal="false" title="调整采购单主体" v-model="visible" align-center width="500px" :z-index="2000" @close="handleClose">
    <el-form label-width="100px" label-position="top">
      <el-form-item label="采购单">
        <VSelect v-model="form.purchase_no" multiple :options="purchaseOptions" placeholder="请选择" class="w-full" />
      </el-form-item>
      <el-form-item label="是否退税">
        <el-radio v-model="form.is_drawback" :value="2">退税</el-radio>
        <el-radio v-model="form.is_drawback" :value="1">不退税</el-radio>
      </el-form-item>
      <el-form-item label="公司主体">
        <VSelect v-model="form.company_id" :options="options.company_id || []" placeholder="请选择" class="w-full"
          @change="companyChange" />
      </el-form-item>
      <el-form-item label="调整后仓库">
        <VSelect v-model="form.destination_warehouse" :options="warehouseOptions" filterable clearable placeholder="请选择"
          class="w-full" />
      </el-form-item>
      <el-form-item label="调整原因">
        <el-input v-model="form.adjust_reason" placeholder="调整原因" type="textarea"
          :autosize="{ minRows: 2, maxRows: 5 }" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import XEUtils from 'xe-utils';
import api from '../api'
import { warehouse } from '@/api/public'
import { ElMessage } from 'element-plus'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
})

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const form = ref({})
const purchaseOptions = ref([])
const warehouseOptions = ref([])

const emit = defineEmits(['close','success'])

const companyChange = tenant_id => {
  warehouse({ tenant_id }).then(res => {
    warehouseOptions.value = res.data
  })
}

// 打开弹窗
const open = async (row) => {
  const { demand_no, purchase, sku, pds_id } = row
  purchaseOptions.value = purchase.map(d => ({ label: d.purchase_no, value: d.purchase_no }))
  const purchaseFirst = purchaseOptions.value[0]?.value
  form.value = { purchase_no: purchaseFirst ? [purchaseFirst] : [], source_type: 1, source_no: demand_no, source_sku: sku, source_id: pds_id }
  if (!load.value) {
    load.value = true
    await 1
  }
  loadings = reactive({})
  visible.value = true
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
// 提交
const submit = () => {
  loadings.submit = true
  api.applyAdjust(form.value).then(res => {
    emit('success')
    close()
  }).finally(() => {
    loadings.submit = false
  })
}

defineExpose({ open })
</script>